<template>
  <a-modal
    :title="(model&&model.id) ? '编辑banner': '新增banner'"
    :width="960"
    :visible="visible"
    :confirmLoading="loading"
    @ok="handleOK"
    @cancel="() => { $emit('cancel') }">
    <a-spin :spinning="loading">
      <a-form :form="form" v-bind="formLayout">
        <!-- 检查是否有 id 并且大于0，大于0是修改。其他是新增，新增不显示主键ID -->
        <a-form-item label="id" style="display: none;">
          <a-input v-decorator="['id']" />
        </a-form-item>
        
        <a-form-item label="banner类型">
          <a-radio-group name="radioGroupType" v-decorator="['type', { rules: [{ required: true, message: '请选择【banner类型】' }] }]">
            <a-radio :value="2">图片</a-radio>
            <a-radio :value="1">视频</a-radio>
          </a-radio-group>
        </a-form-item>
        
        <a-form-item label="banner位置">
          <a-radio-group name="radioGroupPosition" v-decorator="['position', { rules: [{ required: true, message: '请选择【banner位置】' }] }]">
            <a-radio :value="1">首页</a-radio>
            <a-radio :value="2">企业培训</a-radio>
            <a-radio :value="3">AI考证</a-radio>
            <a-radio :value="4">课程</a-radio>
            <a-radio :value="5">我的</a-radio>
            <a-radio :value="6">PC首页</a-radio>
          </a-radio-group>
        </a-form-item>
        
        <a-form-item label="banner图片">
          <a-upload
            name="file"
            list-type="picture-card"
            class="avatar-uploader"
            accept="image/png, image/jpeg, video/*"
            :show-upload-list="false"
            :action="uploadApi"
            @change="handleChange"
            v-decorator="[
              'url',
              {
                valuePropName: 'file',
                getValueFromEvent: normFile,
                rules: [{ required: true, message: '请上传图片/视频' }]
              },
            ]">
            <img v-if="type && type==2 && fileList && fileList[0]" :src="fileList[0].response.data.src" alt="avatar" width="690" height="280"/>
            <video v-else-if="type && type==1 && fileList && fileList[0]" :src="fileList[0].response.data.src" alt="avatar" width="690" height="280"/>
            <div v-else>
              <a-icon type="plus" />
              <div class="ant-upload-text">
                上传
              </div>
            </div>
          </a-upload>
          <a-icon class="loading" type="loading" v-if="bannerLoading"/>
          <div class="tips">建议尺寸: 750x160</div>
        </a-form-item>
        
        <a-form-item label="跳转类型">
          <a-radio-group name="radioGroup" @change="handleType" v-decorator="['toType', { rules: [{ required: true, message: '请选择【跳转类型】' }] }]">
            <a-radio :value="0">
              无跳转
            </a-radio>
<!--            <a-radio :value="1">
              内部跳转
            </a-radio>
            <a-radio :value="2">
              外部链接
            </a-radio> -->
          </a-radio-group>
        </a-form-item>
        
        <a-form-item label="内部跳转"  v-show="toType===1">
          <a-select
            style="width: 180px"
            v-model="shopId"
            @change="getGoods"
            placeholder="请选择商铺">
            <a-select-option v-for="item in shopList" :value="item.id">{{ item.name }}</a-select-option>
          </a-select>
          <a-select
            style="width: 180px;margin-left: 10px;"
            v-decorator="[
              'toId'
            ]"
            placeholder="请选择商品">
            <a-select-option v-for="item in goodsList" :value="item.id">{{ item.name }}</a-select-option>
          </a-select>
          <div><span class="notice-text">*</span> 温馨提示：只有在选择跳转商品后才需要配置</div>
        </a-form-item>
        
        <a-form-item label="状态">
          <a-radio-group name="radioGroupState" v-decorator="['state', { rules: [{ required: true, message: '请选择【状态】' }] }]">
            <a-radio :value="1">激活</a-radio>
            <a-radio :value="2">冻结</a-radio>
          </a-radio-group>
        </a-form-item>
        
      </a-form>
    </a-spin>
  </a-modal>
</template>

<script>
import pick from 'lodash.pick'
import locale from 'ant-design-vue/es/date-picker/locale/zh_CN'
import api from '@/api/banner'
import { shopList, goodsList } from '@/api/banner'
import moment from 'moment'
// 表单字段
const fields = ['type', 'position', 'url', 'state', 'id', 'toType', 'toId']
const baseApi = process.env.VUE_APP_API_BASE_URL
// import UploadPreview from '@/components/upload-prevew'
export default {
  components: { },
  props: {
    visible: {
      type: Boolean,
      required: true
    },
    loading: {
      type: Boolean,
      default: () => false
    },
    model: {
      type: Object,
      default: () => null
    }
  },
  data () {
    this.formLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 3 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 18 }
      }
    }
    return {
      form: this.$form.createForm(this),
      fileList: [],
      contentList: [],
      toType: '',
      // imageUrl: '',
      bannerLoading: false,
      contentLoading: false,
      locale: locale,
      uploadApi: baseApi + api.upload,
      startTime: '',
      endTime: '',
      content: '',
      shopId: undefined,
      goodsList: [],
      shopList: [],
      type: null
    }
  },
  created () {
    // 防止表单未注册
    fields.forEach(v => this.form.getFieldDecorator(v))
    
    // 当 model 发生改变时，为表单设置值
    this.$watch('model', () => {
      if (this.model) {
        this.type=this.model.type
        this.toType = this.model.toType
        this.fileList = [{ response: { data: { src: this.model.url } }, uid: '-' + this.model.id, name: this.model.id, status: 'done' }]
        this.form.setFieldsValue(pick(this.model, fields))
      }
    })
  },
  methods: {
    handleChange (info) {
      if (info.file.status === 'uploading') {
        this.bannerLoading = true
        return
      }
      if (info.file.status === 'done') {
        this.fileList = info.fileList.slice(-1)
        this.bannerLoading = false
      }
    },
    normFile (e) {
      if (e.file.response && e.file.response.data) {
        // this.form.setFieldsValue({ srcSave: e.file.response.data.srcSave })
        this.type = this.form.getFieldsValue().type
        return e.file.response.data.src
      }
      return ''
    },
    async getShops () {
      const res = await shopList()
      if (!res.success) return
      this.shopList = res.data
    },
    async getGoods (id) {
      const res = await goodsList({ id })
      if (!res.success) return
      this.goodsList = res.data
    },
    contentFile () {
      const fileList = this.contentList
      if (fileList.length > 0) {
        const arr = fileList.map(i => i.response.data.src)
        return arr.join(',')
      } else {
        return ''
      }
    },
    handlePreview (e) {
      window.open(e.response.data.src, '_blank')
    },
    handleDelete (index) {
      this.contentList.splice(index, 1)
      const str = this.contentFile()
      this.form.setFieldsValue({ content: str })
    },
    handleType(e) {
      this.toType = e.target.value
    },
    changeBegin (e) {
      this.startTime = e
    },
    changeEnd (e) {
      this.endTime = e
    },
    disabledBeginDate (e) {
      if (this.endTime) {
        return !(e > moment().startOf('day') && e < moment(this.endTime))
      }
      return e < moment().startOf('day')
    },
    disabledEndDate (e) {
      // console.log('disabledEndDate', e)
      return this.startTime ? e < moment(this.startTime) : e < moment().startOf('day')
    },
    handleOK () {
      this.$emit('ok')
    }
  }
}
</script>
<style scoped lang="less">
.avatar-uploader > .ant-upload {
  width: 128px;
  height: 128px;
}
.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}
.upload-wrapper {
  display: flex;
}
.img-list {
  display: flex;
  .img-item {
    position: relative;
    width: 100px;
    height: 100px;
    padding: 4px;
    overflow: hidden;
    box-sizing: border-box;
    margin-right: 10px;
    border-radius: 10px;
    overflow: hidden;
    &:hover .img-list .img-item .mask{
      display: block;
    }
    .img {
      height: 100%;
      width: 100%;
    }
  }
  .upload-btn {
    width: 100px;
    height: 100px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;

  }
  .myicon {
    font-size: 20px;
    color: #fff;
    &:hover {
      color: #1890ff;
    }
  }
  .mask {
    display: none;
    position: absolute;
    height: 100%;
    width: 100%;
    background-color: rgba(0, 0, 0, .65);
    left: 0;
    top: 0;
    display: flex;
    align-items: center;
    justify-content: space-around;
  }
}
.notice-text {
  color: #f5222d;
}

</style>
